package com.atguigu.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils2 {
    static String url;
    static String driverClass;
    static String password;
    static String username;
    static {
        //创建properties读取配置文件
        Properties p = new Properties();
        //创建流
        InputStream is = JDBCUtils2.class.getClassLoader().getResourceAsStream("jdbc.properties");
        //加载流
        try {
            p.load(is);
            url = p.getProperty("url");
            driverClass = p.getProperty("driverClass");
            password = p.getProperty("password");
            username = p.getProperty("username");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (is!=null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static  Connection getConnect() {
        try {
            //Driver类加载
            Class.forName(driverClass);
            Connection connection = DriverManager.getConnection(url, username, password);

            return connection;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
    public static void close(Connection connection, PreparedStatement ps){
        try {
            if (connection!=null) {
                connection.close();
            }
            if (ps!=null) {
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection connect, PreparedStatement ps, ResultSet resultSet) {
            close(connect,ps);
        try {
            if (resultSet!=null) {
                resultSet.close();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
